<?php

require '../vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
use PhpOffice\PhpSpreadsheet\Writer\Xls;
use PhpOffice\PhpSpreadsheet\Style\Alignment;

function getLetterArray($key = '')
{
    $letterArray = range('A', 'Z'); // 26个字母数组 下标从0开始
    if (isset($letterArray[$key])) {
        return $letterArray[$key];
    }

    return $letterArray;
}

function getColumnArray($key = '')
{
    $columnName = [
        ['width' => 25, 'name' => '文件夹名'],
        ['width' => 30, 'name' => '文件名'],
        ['width' => 10, 'name' => '文件说明'],
    ];
    if (isset($columnName[$key])) {
        return $columnName[$key];
    }
    return $columnName;
}
/**
 * 将目录中的xml中数据解析并保存到excel文件中
 * 用到的第三方excel插件：composer require phpoffice/phpspreadsheet
 *
 * @param array $data 数据
 * @param string $savePath 保存目录
 * @param string $saveName 文件名
 * @param string $extension 文件扩展名
 * @throws \PhpOffice\PhpSpreadsheet\Exception
 * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
 *
 * @Author: 雲溪荏苒 <290648237@qq.com>
 */
function saveExcel($data, $savePath = 'excel/', $saveName = '', $extension = '.xls')
{
    $spreadsheet = new Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();
    $sheet->setTitle('记录文件');

    //设置excel列名及列其他参数
    foreach (getColumnArray() as $k=>$item)
    {
        $letter = (string)getLetterArray($k);
        // 设置excel列名
        $spreadsheet->setActiveSheetIndex(0)->setCellValue($letter.'1', $item['name']);
        // 设置列宽度
        $spreadsheet->getActiveSheet()->getColumnDimension($letter)->setWidth($item['width']);
    }

    //把数据循环写入excel中
    $key = 0;
    foreach($data as $dir => $filename){
        $key += 1;
        $spreadsheet->setActiveSheetIndex(0)
            ->setCellValue('A'.($key+1), $dir)
            ->setCellValue('B'.($key+1), implode(' ', array_unique($filename)))
            ->setCellValue('C'.($key+1), '')
        ;

        // 设置自动筛选
        $spreadsheet->getActiveSheet()->setAutoFilter($spreadsheet->getActiveSheet()->calculateWorksheetDimension());
    }

    // 保存excel文件到指定文件夹
    if (!is_dir(__DIR__.DIRECTORY_SEPARATOR.$savePath)) {
        mkdir(__DIR__.DIRECTORY_SEPARATOR.$savePath, '0744');
    }
    $writer = new Xls($spreadsheet);
    $writer->save($savePath.$saveName.$extension);

    /*download*/
    // Redirect output to a client’s web browser (Xls)
//    header('Content-Type: application/vnd.ms-excel');
//    header('Content-Disposition: attachment;filename="'.$saveName.$extension.'"');
//    header('Cache-Control: max-age=0');
//// If you're serving to IE 9, then the following may be needed
//    header('Cache-Control: max-age=1');
//
//// If you're serving to IE over SSL, then the following may be needed
//    header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
//    header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
//    header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
//    header('Pragma: public'); // HTTP/1.0
//    $writer = IOFactory::createWriter($spreadsheet, 'Xls');
//    $writer->save('php://output');
    exit;
}


//递归方式
function read_dir($dir){
    $files=array();
    $dir_list=scandir($dir);
    foreach($dir_list as $file){
        if($file!='..' && $file!='.'){
            if(is_dir($dir.'/'.$file)){
                $files[]=read_dir($dir.'/'.$file);
            }else{
                $files[]=$file;
            }
        }
    }
    return $files;
}

//队列方式 此方法暂时无用
function read_dir_queue($dir){
    $files=array();
    $queue=array($dir);
    while($data=each($queue)){
        $path=$data['value'];
        if(is_dir($path) && $handle=opendir($path)){
            while($file=readdir($handle)){
                if($file=='.'||$file=='..') continue;
                $files[] = $real_path=$path.'/'.$file;
                if (is_dir($real_path)) $queue[] = $real_path;
            }
        }
        closedir($handle);
    }
    return $files;
}


// 遍历目录及文件
$base_dir = 'D:\laragon\www\php\theme_dir\theme\default';
$dir_file_list = str_replace('/', '\\', read_dir_queue($base_dir));
$dir_arr = $file_arr = $dir_all = [];
$filename = '';
$xmlContent = [];
$dirArr = [];
foreach ($dir_file_list as &$item) {
    $dir_file_arr = explode($base_dir, $item);



    if (is_file($item)) {
        $filename = basename($item);
    }

    $short_path = explode($base_dir, rtrim($item, $filename))[1];
    $full_dir_path = $base_dir.$short_path;
    $dir_all[$short_path] = $filename;

    if (is_file($item) && strpos($item, '.html')) {
        $xmlContent[basename($item)] = $item;
        $dirArr[$short_path][] = $filename;
//        $dirArr[$short_path] = $filename.' '.$filename;
    }
}

$spreadsheet = $dirArr;

$savePath = 'excel/'; // 保存目录
$saveName = date('Ymd'); // 保存文件名 不带后缀（已默认设置为.xls）
saveExcel($spreadsheet, $savePath, $saveName);
